package cn.cangfei.massage.controller;

import cn.cangfei.massage.common.api.CommonPage;
import cn.cangfei.massage.common.api.CommonResult;
import cn.cangfei.massage.dto.VisitDoctorPlanDTO;
import cn.cangfei.massage.dto.VisitPlanDTO;
import cn.cangfei.massage.dto.VisitPlanResiduesDTO;
import cn.cangfei.massage.dto.param.VisitPlanParam;
import cn.cangfei.massage.dto.param.VisitPlanUpdateParam;
import cn.cangfei.massage.dto.update.AppointmentForDoctor;
import cn.cangfei.massage.entity.Jia;
import cn.cangfei.massage.entity.UpdateDay;
import cn.cangfei.massage.service.IMassageDoctorService;
import cn.cangfei.massage.service.IMassageInfoService;
import cn.cangfei.massage.service.IVisitPlanService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Lemon  2313812755@qq.com
 * @date 2023/3/2
 */

@Api(value = "出诊模块", tags = "出诊计划接口")
@RestController
@CrossOrigin
@RequestMapping("/visit")
public class VisitPlanController {

    @Resource
    private IVisitPlanService planService;

    @Resource
    private IMassageInfoService massageInfoService;

    @Resource
    private IMassageDoctorService massageDoctorService;


    // TODO 开启定时任务
    @ApiOperation(value = "定时扫描请假表来进行删除的", notes = "")
    @RequestMapping(value = "/removeJia", method = RequestMethod.GET)
    public CommonResult deleteJia() {


        planService.deleteJia();


        return CommonResult.success();
    }

    @ApiOperation(value = "修改上班每周的接口", notes = "")
    @RequestMapping(value = "/updateDay", method = RequestMethod.POST)
    public CommonResult updateDay(@RequestBody UpdateDay updateDay) {


        planService.updateDay(updateDay);


        return CommonResult.success();
    }


    @ApiOperation(value = "请假接口", notes = "")
    @RequestMapping(value = "/getJia", method = RequestMethod.POST)
    public CommonResult getJia(@RequestBody Jia jia) {


        planService.getJia(jia);


        return CommonResult.success();
    }


    @ApiOperation(value = "添加出诊计划", notes = "传入 出诊计划参数（推拿馆编号、专科编号、门诊编号、诊室编号、师傅编号、出诊时间段（1：上午，2：下午）、出诊日期）")
    @RequestMapping(value = "/plan", method = RequestMethod.POST)
    public CommonResult insertVisitPlan(@RequestBody VisitPlanParam param) {

        if (!massageDoctorService.count(param.getDoctorId())) {
            return CommonResult.validateFailed("不存在，该师傅编号！");
        }

        if (!massageInfoService.count(param.getMassageId())) {
            return CommonResult.validateFailed("不存在，该推拿馆编号！");
        }


        if (planService.insertAll(param)) {
            return CommonResult.success();
        }

        return CommonResult.failed("服务器错误，请联系管理员！");
    }

    @ApiOperation("得到时间段")
    @RequestMapping(value = "/doctorId/{id}", method = RequestMethod.PUT)
    public CommonResult<String> get(@PathVariable Long id) {
        return CommonResult.success(planService.getDuan(id));
    }


    @ApiOperation(value = "更新出诊计划", notes = "传入 出诊编号、出诊计划参数（推拿馆编号、专科编号、门诊编号、诊室编号、师傅编号、出诊日期）")
    @ApiImplicitParam(name = "id", value = "出诊编号", paramType = "path", dataType = "Long", required = true)
    @RequestMapping(value = "/plan/{id}", method = RequestMethod.PUT)
    public CommonResult updateVisitPlan(@PathVariable Long id, @RequestBody VisitPlanUpdateParam param) {

        if (!massageDoctorService.count(param.getDoctorId())) {
            return CommonResult.validateFailed("不存在，该师傅编号！");
        }

        if (!massageInfoService.count(param.getMassageId())) {
            return CommonResult.validateFailed("不存在，该推拿馆编号！");
        }


        if (planService.update(id, param)) {
            return CommonResult.success();
        }

        return CommonResult.failed("服务器错误，请联系管理员！");
    }

    @ApiOperation(value = "搜索出诊计划", notes = "传入 推拿馆编号、专科编号、门诊编号、出诊日期、第几页、页大小")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "massageId", value = "推拿馆编号", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "specialId", value = "专科编号", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "outpatientId", value = "门诊编号", paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "day", value = "出诊日期", paramType = "query", dataType = "String",
                    required = true),
            @ApiImplicitParam(name = "pageNum", value = "第几页", paramType = "query", dataType = "Integer",
                    required = true),
            @ApiImplicitParam(name = "pageSize", value = "页大小", paramType = "query", dataType = "Integer",
                    required = true),
    })
    @RequestMapping(value = "/plan/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<VisitPlanDTO>> searchVisitPlan(@RequestParam(required = false) Long massageId,
                                                                  @RequestParam(required = false) Long specialId,
                                                                  @RequestParam(required = false) Long outpatientId,
                                                                  @RequestParam String day,
                                                                  @RequestParam Integer pageNum,
                                                                  @RequestParam Integer pageSize) throws ParseException {

        // 根据这个day来判断是星期几
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        Date date = formatter.parse(day);

        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        // week表示星期
        String week = weekDays[w];

        return CommonResult.success(CommonPage.restPage(planService.list(massageId, specialId, outpatientId, null,
                week, pageNum, pageSize)));
    }

    @ApiOperation(value = "删除出诊计划", notes = "传入 出诊编号")
    @ApiImplicitParam(name = "id", value = "出诊编号", paramType = "path", dataType = "Long", required = true)
    @RequestMapping(value = "/plan/{id}", method = RequestMethod.DELETE)
    public CommonResult deleteVisitPlan(@PathVariable Long id) {

        if (!planService.count(id)) {
            return CommonResult.validateFailed("不存在，该出诊编号");
        }

        if (planService.delete(id)) {
            return CommonResult.success();
        }

        return CommonResult.failed("服务器错误，请联系管理员！");
    }

    @ApiOperation(value = "批量删除出诊计划", notes = "传入 出诊编号列表")
    @ApiImplicitParam(name = "id", value = "出诊编号列表", paramType = "query", dataType = "List<Long>", required = true)
    @RequestMapping(value = "/plan/all", method = RequestMethod.DELETE)
    public CommonResult deleteAllVisitPlan(@RequestParam List<Long> idList) {

        if (CollUtil.isEmpty(idList)) {
            return CommonResult.validateFailed("出诊编号列表为空！");
        }

        if (planService.deleteAll(idList)) {
            return CommonResult.success();
        }

        return CommonResult.failed("服务器错误，请联系管理员！");
    }

    @ApiOperation(value = "根据师傅，获取出诊信息", notes = "传入 师傅编号、开始日期、结束日期")
    @RequestMapping(value = "/plan/doctor", method = RequestMethod.GET)
    public CommonResult<VisitDoctorPlanDTO> searchVisitPlanByDoctor(@RequestParam Long doctorId,
                                                                    @RequestParam String startDate,
                                                                    @RequestParam String endDate) {

        if (!massageDoctorService.count(doctorId)) {
            return CommonResult.validateFailed("不存在，该师傅编号！");
        }

        Date start = DateUtil.parseDate(startDate);
        Date end = DateUtil.parseDate(endDate);

        if (start.getTime() > end.getTime()) {
            return CommonResult.validateFailed("不存在，该日期时间段");
        }

        return CommonResult.success(planService.getDoctorPlan(doctorId, start, end));
    }

    @ApiOperation(value = "根据推拿馆编号、师傅编号、日期，获取出诊信息", notes = "传入 师傅编号、日期")
    @RequestMapping(value = "/plan/doctor/date", method = RequestMethod.GET)
    public CommonResult<List<VisitPlanResiduesDTO>> searchVisitPlanByDoctorAndDate(@RequestParam Long massageId,
                                                                                   @RequestParam Long doctorId,
                                                                                   @RequestParam String date) throws ParseException {

        if (!massageInfoService.count(massageId)) {
            return CommonResult.validateFailed("不存在，该推拿馆编号！");
        }

        if (!massageDoctorService.count(doctorId)) {
            return CommonResult.validateFailed("不存在，该师傅编号！");
        }

//        Date time = DateUtil.parseDate(date);

        // 根据这个day来判断是星期几
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        Date d = formatter.parse(date);

        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        // week表示星期
        String week = weekDays[w];

        return CommonResult.success(planService.getDoctorPlanByDate(massageId, doctorId, week, date));
    }

    @ApiOperation(value = "根据师傅编号查询这个星期的预约人数情况", notes = "传入 师傅编号")
    @RequestMapping(value = "/plan/doctor/appointment/date", method = RequestMethod.GET)
    public CommonResult<List<AppointmentForDoctor>> searchVisitPlanByDoctorAndDateAndWeek(@RequestParam Long doctorId) {

        // 需要返回每天
        return CommonResult.success(planService.searchVisitPlanByDoctorAndDateAndWeek(doctorId));
    }


}
